package org.iabako.server.serviceimpl.user;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.iabako.server.dao.JpaDAO;
import org.iabako.server.dao.business.QueryDefinitionDAO;
import org.iabako.server.dao.user.EnterpriseDAO;
import org.iabako.server.dao.user.UserDAO;
import org.iabako.server.dao.user.UserPayPalTokenDAO;
import org.iabako.server.serviceimpl.business.AbstractServiceImpl;
import org.iabako.server.tools.BundleMessages;
import org.iabako.server.tools.ServerTools;
import org.iabako.shared.entity.business.*;
import org.iabako.shared.entity.enumeration.EnterpriseTrackType;
import org.iabako.shared.entity.enumeration.IabakoPackage;
import org.iabako.shared.entity.user.*;
import org.iabako.shared.exception.IabakoPackageForbiddenException;
import org.iabako.shared.exception.IabakoUniqueConstraintException;
import org.iabako.shared.iservice.business.NotificationService;
import org.iabako.shared.iservice.business.PaymentRequestService;
import org.iabako.shared.iservice.security.AuthenticateService;
import org.iabako.shared.iservice.user.SignUpService;
import org.iabako.shared.iservice.user.UserService;
import org.iabako.shared.querydefinition.SearchMotorQueryEnum;
import org.iabako.shared.querydefinition.columndefinition.UserColumnEnum;
import org.iabako.shared.querydefinition.dto.QueryDefinitionDTO;
import org.iabako.shared.querydefinition.dto.QueryOperatorEnum;
import org.iabako.shared.tools.GenericTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by jose on 24/09/14.
 */

@Service("userService")
public class UserServiceImpl extends AbstractServiceImpl implements UserService {

    static Logger log = Logger.getLogger(UserServiceImpl.class.getName());

    @Autowired
    UserDAO userDAO;
    @Autowired
    EnterpriseDAO enterpriseDAO;
    @Autowired
    PaymentRequestService paymentRequestService;
    @Autowired
    QueryDefinitionDAO queryDefinitionDAO;
    @Autowired
    UserPayPalTokenDAO userPayPalTokenDAO;
    @Autowired
    BundleMessages messages;
    @Autowired
    AuthenticateService authenticateService;
    @Autowired
    SignUpService signUpService;
    @Autowired
    NotificationService notificationService;

    static private final Random random = new Random();

    @Override
    protected JpaDAO getDAO() {
        return userDAO;
    }

    public QueryDefinitionDTO getSearchQueryDefinitionDTO(QueryDefinitionDTO qd) {
        qd.setSearchMotorQuery(SearchMotorQueryEnum.UserSearch);
        qd.addCriteria(UserColumnEnum.enterprise, QueryOperatorEnum.IN, (ArrayList) getSessionUser().getEnterprise().getVisibleEnterprises());
        qd.addCriteria(UserColumnEnum.id, QueryOperatorEnum.NOT_EQUALS, getSessionUser().getId());
        qd.addCriteria(UserColumnEnum.active, QueryOperatorEnum.EQUALS, true);

        queryDefinitionDAO.executeQueryDefinition(qd);
        return qd;
    }

    public QueryDefinitionDTO setSearchCriteriaFromSuggest(QueryDefinitionDTO qd, Long hiddenSelectionCode, String suggestionValue) {
        return null;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public User getUserByEmail(String username) {
        User user = userDAO.getUserByEmail(username);

        if (user != null) {
            user.setLastLogin(new Date());
            Hibernate.initialize(user.getEnterprise());
            EnterpriseBalance enterpriseBalance = user.getEnterprise().getEnterpriseBalance();
            if (enterpriseBalance != null) {
                //In first login EnterpriseBalance is NULL here (it must be reloaded/created later)
                enterpriseBalance.setEnterpriseTracks(userDAO.getEnterpriseTracks(enterpriseBalance));
            }
            reloadEnterpriseBalance(user.getEnterprise(), false);
            reloadNotifications(user.getEnterprise(), false);
            user.copyDatesAsString();
        }
        return user;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private void reloadEnterpriseBalance(Enterprise enterprise, boolean forced) {
        ServerTools serverTools = new ServerTools();
        Date today = serverTools.resetTime(new Date());

        EnterpriseBalance enterpriseBalance = getEnterpriseBalance(enterprise);
        User user = enterpriseDAO.getPrincipalUser(enterprise);

        if (forced
                || enterpriseBalance == null
                || (enterpriseBalance.getEndDate().compareTo(today) < 0 && user.getUserCredit().getExpirationDate().compareTo(today) >= 0)) {

            enterpriseBalance = new EnterpriseBalance();

            Date expirationDate = forced ? serverTools.addDaysToDate(today, -1) : serverTools.resetTime(user.getUserCredit().getExpirationDate());

            Date balanceEndDate;
            if (expirationDate.compareTo(today) <= 0) {
                balanceEndDate = (Date) expirationDate.clone();
            } else {
                balanceEndDate = (Date) expirationDate.clone();
                int decreaseCounter = 0;
                while (balanceEndDate.compareTo(today) > 0) {
                    balanceEndDate = serverTools.addMonthsToDate((Date) expirationDate.clone(), --decreaseCounter);
                }
                balanceEndDate = serverTools.addMonthsToDate((Date) expirationDate.clone(), decreaseCounter + 1);
            }
            enterpriseBalance.setEndDate(balanceEndDate);
            Date endMinesOneMonth = serverTools.addMonthsToDate((Date) balanceEndDate.clone(), -1);
            enterpriseBalance.setStartDate(serverTools.addDaysToDate(endMinesOneMonth, 1));

            enterprise.setEnterpriseBalance(enterpriseBalance);

            super.save(enterprise);
        }

        enterpriseBalance.calculateSubTracking();
    }

    /**
     * This method recalculate Notifications at :
     * 1. Login (once a day)
     * 2. Email Notification recap (once a day early in the morning)
     * 3. Notification config modification (every time)
     *
     * @param enterprise
     * @param forced     true if recalculation must be done every time. false if it's just once a day.
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void reloadNotifications(Enterprise enterprise, boolean forced) {
        if (forced || enterprise.getLastNotificationCalculation() == null ||
                enterprise.getLastNotificationCalculation().compareTo(new ServerTools().resetTime(new Date())) < 0) {

            List<Notification> oldNotifications = notificationService.getNotifications(enterprise);
            List<Notification> newNotifications = notificationService.calculateNotifications(enterprise);

            //Conserve hidden users configuration if Notification has not changed.
            for (Notification oldNotif : oldNotifications) {
                for (Notification newNotif : newNotifications) {
                    if (oldNotif.getType() == newNotif.getType()
                            && oldNotif.getCardinal() == newNotif.getCardinal()) {
                        newNotif.getHiddenUsers().addAll(oldNotif.getHiddenUsers());
                        break;
                    }
                }
            }

            enterprise.getNotificationList().clear();
            enterprise.getNotificationList().addAll(newNotifications);

            enterprise.setLastNotificationCalculation(new Date());
            enterprise = signUpService.saveEnterprise(enterprise);

            if (forced && getEnterpriseFromSessionUser() != null) {
                getSessionUser().setEnterprise(enterprise);
            }

        } else if (enterprise.getNotificationList().isEmpty()) {
            enterprise.getNotificationList().addAll(notificationService.getNotifications(enterprise));
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean remove(Long id) {
        userDAO.detachRelatedObjects(id);
        enterpriseDAO.detachLimitedVisibilityEnterprises(id);
        return super.remove(id);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public User save(User user) throws IabakoUniqueConstraintException {

        User userByEmail = userDAO.getUserByEmail(user.getEmail());

        if (userByEmail != null) {
            if (user.getId() == null) {
                throw new IabakoUniqueConstraintException("validation_user_creation_unique_constraint_error_title",
                        messages.getLabel("validation_user_creation_unique_constraint_error_text", user.getEmail()), false, false);

            } else if (!user.equals(userByEmail)) {
                throw new IabakoUniqueConstraintException("validation_user_modification_unique_constraint_error_title",
                        "validation_user_modification_unique_constraint_error_text", false, false);
            }
        }

        if (user.isActive()) {
            //if user is active, we can delete other users with same email (they become useless in marketing)
            userDAO.deleteNoActiveUsersWithSameEmail(user.getEmail());
        }

        if (user.getEnterprise() == null) {
            //User creation
            user.setEnterprise(getEnterpriseFromSessionUser());
        }

        if (user.isLimitedVisibility() && user.getId() == null) {
            createNewChildEnterprise(user);
        }

        user = (User) super.save(user);

        Hibernate.initialize(user.getEnterprise());
        Hibernate.initialize(user.getUserPayPalToken());
        Hibernate.initialize(user.getUserPayPalToken() != null ? user.getUserPayPalToken().getPayer() : null);

        if (getSessionUser() != null && user.getId().equals(getSessionUser().getId())
                && user.getEmail().equals(getSessionUser().getEmail())) {
            //Same user (and email didn't change
            authenticateService.reloadAuthenticatedUser();
        }

        return user;
    }

    private void createNewChildEnterprise(User user) {
        Enterprise parentEnterprise = getEnterpriseFromSessionUser();
        Enterprise newEnterprise = new Enterprise();
        newEnterprise.setName(parentEnterprise.getName());
        newEnterprise.setEmail(parentEnterprise.getEmail());
        newEnterprise.setAddress(parentEnterprise.getAddress());
        newEnterprise.setPhoneNumber(parentEnterprise.getPhoneNumber());
        newEnterprise.setWebSite(parentEnterprise.getWebSite());
        newEnterprise.setLanguage(parentEnterprise.getLanguage());
        newEnterprise.setParentEnterprise(parentEnterprise);

        //Notifications are made by Enterprise (each Enterprise has its own NotificationConfig)
        newEnterprise.setNotificationConfig(parentEnterprise.getNotificationConfig().customClone());

        newEnterprise = (Enterprise) super.save(newEnterprise);

        newEnterprise.getUsers().add(user);
        user.setEnterprise(newEnterprise);

        parentEnterprise.setChildrenEnterprises(enterpriseDAO.getChildrenEnterprises(parentEnterprise));
        parentEnterprise.setAllRelatedEnterprise(enterpriseDAO.getAllRelatedEnterprises(parentEnterprise));
        parentEnterprise.setUsersNumber(enterpriseDAO.getUsersNumber(parentEnterprise));

        paymentRequestService.copyPaymentRequestConfig(parentEnterprise, newEnterprise);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void setUserPayPalTokenPayed(String iabakoTxId, String payPalPayerEmail, String payPalResponse) {
        UserPayPalToken userPayPalToken = userPayPalTokenDAO.getUserPayPalTokenByTxId(iabakoTxId);

        if (userPayPalToken != null && !userPayPalToken.isPayed()) {
            log.info("A new payment has been received : " + iabakoTxId);

            //If token was to verify, credit was already taken into account before
            boolean updateCredit = !userPayPalToken.isToVerify();

            userPayPalToken.setToVerify(false);
            userPayPalToken.setPayed(true);

            payPalResponse = payPalResponse.length() > 999 ? payPalResponse.substring(0, 999) : payPalResponse;
            userPayPalToken.setPayPalResponse(payPalResponse);
            userPayPalToken.setPayPalPayerEmail(payPalPayerEmail);

            if (updateCredit) {
                updateCredits(userPayPalToken);
            }

            userPayPalTokenDAO.merge(userPayPalToken);

        } else {
            log.warn("This payment does not exist or has been already received : " + iabakoTxId);
        }
    }

    private void updateCredits(UserPayPalToken token) {
        List<User> usersToMerge = new ArrayList<User>();
        if (token.isUpgradeCredit()) {
            calculateUserCredit(true, token.getPrincipalUser(), null, token.getQuantity());
            usersToMerge.add(token.getPrincipalUser());

        } else {
            if (token.getQuantity() > 0) {
                //Credit for hole Enterprise
                Date today = new ServerTools().resetTime(new Date());
                if (token.getPrincipalUser().getUserCredit().getExpirationDate().compareTo(today) < 0) {
                    reloadEnterpriseBalance(getSessionUser().getEnterprise(), true);
                }

                calculateUserCredit(false, token.getPrincipalUser(), token.getIabakoPackage(), token.getQuantity());
                usersToMerge.add(token.getPrincipalUser());
            }

            for (UserPayPalTokenUser userToken : token.getUserTokens()) {
                calculateUserCredit(false, userToken.getUser(), token.getPrincipalUser().getUserCredit().getIabakoPackage(), userToken.getQuantity());
                usersToMerge.add(userToken.getUser());
            }
        }

        for (User user : usersToMerge) {
            //Perhaps first user didn't pass through free trial period
            user.setActive(true);

            try {
                save(user);
            } catch (IabakoUniqueConstraintException e) {
                //Should never happen!
                log.error(e.getMessage(), e);
            }
        }
        //This is specially important if this is an upgrade because new credit information is only present in principal user
        getSessionUser().getEnterprise().setPrincipalUser(enterpriseDAO.getPrincipalUser(getSessionUser().getEnterprise()));
    }

    public void calculateUserCredit(boolean upgrade, User user, IabakoPackage iabakoPackage, int quantity) {
        if (user.getUserCredit() == null) {
            user.setUserCredit(new UserCredit());
        }

        ServerTools serverTools = new ServerTools();
        Date today = serverTools.resetTime(new Date());

        UserCredit userCredit = user.getUserCredit();

        if (upgrade) {
            userCredit.setNumberOfUpgrades(userCredit.getNumberOfUpgrades() + 1);

        } else {
            userCredit.setNumberOfUpgrades(0);
            userCredit.setIabakoPackage(iabakoPackage);

            if (userCredit.getExpirationDate().compareTo(today) < 0) {
                //Credit starts today
                userCredit.setExpirationDate(serverTools.addDaysToDate(today, -1));
            }
            for (int i = 0; i < quantity; i++) {
                //If this is not a principal user, credit is always purchase month by month
                int timeInMonths = user.isPrincipal() ? iabakoPackage.getTimeInMonths() : 1;
                Date datePlusNMonth = serverTools.addMonthsToDate((Date) userCredit.getExpirationDate().clone(), timeInMonths);
                userCredit.setExpirationDate(datePlusNMonth);
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void setUserPayPalTokenToVerify(String transactionId, String payPalResponse) {
        UserPayPalToken userPayPalToken = userPayPalTokenDAO.getUserPayPalTokenByTxId(transactionId);
        if (userPayPalToken != null) {
            log.info("This payment must be verified : " + transactionId);

            userPayPalToken.setToVerify(true);
            payPalResponse = payPalResponse.length() > 999 ? payPalResponse.substring(0, 999) : payPalResponse;
            userPayPalToken.setPayPalResponse(payPalResponse);

            updateCredits(userPayPalToken);

            //TODO why we don't send an email ?

            userPayPalTokenDAO.merge(userPayPalToken);

        } else {
            log.warn("This payment does not exist : " + transactionId);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void setUserPayPalTokenCanceled(String transactionId, String payPalResponse) {
        UserPayPalToken userPayPalToken = userPayPalTokenDAO.getUserPayPalTokenByTxId(transactionId);

        if (userPayPalToken != null) {
            log.info("This transaction has been canceled : " + transactionId);

            userPayPalToken.setCanceled(true);
            userPayPalToken.setPayPalResponse(payPalResponse);

            userPayPalTokenDAO.merge(userPayPalToken);

        } else {
            log.warn("This payment does not exist : " + transactionId);
        }
    }

    public List<User> getUsersBySessionEnterprise() {
        return userDAO.getUsersByEnterprise(getEnterpriseFromSessionUser());
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String savePayPalToken(UserPayPalToken payPalToken, List<UserPayPalTokenUser> userTokens) {
        String transactionId = new BigInteger(130, random).toString(32) + new Date().getTime();

        List<User> usersToMerge = new ArrayList<User>();

        if (payPalToken.getQuantity() > 0) {
            payPalToken.getPrincipalUser().setUserPayPalToken(payPalToken);
            usersToMerge.add(payPalToken.getPrincipalUser());
        }

        Double amountTotal = payPalToken.isUpgradeCredit() ? 9 : payPalToken.getQuantity() * payPalToken.getIabakoPackage().getAmount();

        for (UserPayPalTokenUser userToken : userTokens) {
            amountTotal += userToken.getQuantity() * 9;

            userToken.getUser().setUserPayPalToken(payPalToken);
            userToken.setUserPayPalToken(payPalToken);
            usersToMerge.add(userToken.getUser());
        }

        sessionUser.getUser().setGoToPayPal(true);

        payPalToken.setTransactionId(transactionId);
        payPalToken.setUserTokens(userTokens);
        payPalToken.setAmount(amountTotal);
        userPayPalTokenDAO.persist(payPalToken);

        for (User user : usersToMerge) {
            userDAO.merge(user);
        }

        return transactionId;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addInvoiceReceiptToEnterpriseBalance(Sale sale, Payment payment) throws IabakoPackageForbiddenException {

        boolean isInvoice = sale != null;
        User sessionUser = getSessionUser();

        if (sessionUser == null) {
            //Background mode (ex. DB-DEMO installation)
            SaleProductService saleProductService = payment.getSale().getProductsServices().get(0);
            if (saleProductService.getProduct() != null) {
                sessionUser = saleProductService.getProduct().getEnterprise().getUsers().get(0);
            } else {
                sessionUser = saleProductService.getService().getEnterprise().getUsers().get(0);
            }
        }

        EnterpriseBalance enterpriseBalance = getEnterpriseBalance(sessionUser.getEnterprise());
        UserCredit userCredit = getPrincipalUser().getUserCredit();

        boolean newForbidden = isInvoice ?
                enterpriseBalance.isInvoiceForbidden(userCredit)
                : enterpriseBalance.isReceiptForbidden(userCredit);

        if (newForbidden) {
            String packageLabel = messages.getLabel(userCredit.getIabakoPackage().getLabelKey());
            packageLabel = packageLabel.substring(0, packageLabel.indexOf(" "));

            throw new IabakoPackageForbiddenException("action_forbidden_by_package_title",
                    messages.getLabel(isInvoice ? "new_invoice_forbidden_by_package_text" : "new_receipt_forbidden_by_package_text",
                            userCredit.getInvoiceLimit() + "",
                            packageLabel, GenericTools.formatDate(userCredit.getExpirationDate())), "snifficon", true);
        }

        addInvoiceReceipt(isInvoice, enterpriseBalance, sessionUser, sale, payment);
    }

    private void addInvoiceReceipt(boolean isInvoice, EnterpriseBalance enterpriseBalance, User user, Sale sale, Payment payment) {
        if (isInvoice) {
            addInvoiceTrack(enterpriseBalance, user, sale);
        } else {
            addReceiptTrack(enterpriseBalance, user, payment);
        }
    }

    private void addInvoiceTrack(EnterpriseBalance enterpriseBalance, User sessionUser, Sale sale) {
        EnterpriseTrack track = EnterpriseTrack.getFromSale(sessionUser, sale, EnterpriseTrackType.invoiceTrack);
        addPaymentTrack(enterpriseBalance, sessionUser, track);
    }

    private void addReceiptTrack(EnterpriseBalance enterpriseBalance, User sessionUser, Payment payment) {
        EnterpriseTrack track = EnterpriseTrack.getFromPayment(sessionUser, payment, EnterpriseTrackType.receiptTrack);
        addPaymentTrack(enterpriseBalance, sessionUser, track);
    }

    private void addPaymentTrack(EnterpriseBalance enterpriseBalance, User sessionUser, EnterpriseTrack track) {
        track.setEnterpriseBalance(enterpriseBalance);

        enterpriseBalance.getEnterpriseTracks().add(track);
        enterpriseBalance.getInvoiceTracks().add(track);

        super.save(track);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addCommunicationToEnterpriseBalance(ClientCommunication clientCommunication) {

        User sessionUser = getSessionUser();

        EnterpriseBalance enterpriseBalance = getEnterpriseBalance(sessionUser.getEnterprise());

        EnterpriseTrack track = EnterpriseTrack.getFromCommunication(sessionUser, clientCommunication);
        track.setEnterpriseBalance(enterpriseBalance);

        enterpriseBalance.getEnterpriseTracks().add(track);
        enterpriseBalance.getCommunicationTracks().add(track);

        super.save(track);
    }

    private EnterpriseBalance getEnterpriseBalance(Enterprise enterprise) {
        return enterprise.getParentEnterprise() != null ?
                enterprise.getParentEnterprise().getEnterpriseBalance() : enterprise.getEnterpriseBalance();

    }

    public User getPrincipalUser() {
        return enterpriseDAO.getPrincipalUser(sessionUser.getUser().getEnterprise());
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public UserPayPalToken getUserPayPalTokenPayedOrToVerify(String iabakoTxId) {

        UserPayPalToken userPayPalToken = userPayPalTokenDAO.getUserPayPalTokenByTxId(iabakoTxId);

        return userPayPalToken == null ||
                (!userPayPalToken.isPayed() && !userPayPalToken.isToVerify()) ? null : userPayPalToken;
    }


    /* This is for test

    public static void main(String[] args) throws IOException, URISyntaxException {
        HttpClient client = HttpClientBuilder.create().build();

        URIBuilder builder = new URIBuilder("https://api-3t.sandbox.paypal.com/nvp")
                .addParameter("USER", "iabakoproject-facilitator_api1.gmail.com")
                .addParameter("PWD", "8Z2B6EPNY7TXNF6Z")
                .addParameter("SIGNATURE", "ArzLbDkEAt8X0WpsQfXHZNFHGeJDAJYpgvPKnLwZhBq0VM5s062WuicY")
                .addParameter("METHOD", "TransactionSearch")
                .addParameter("VERSION", "95.0")
                .addParameter("INVNUM", "iainqir635ssqe14gs6h7ar7g31418823792888")
                .addParameter("STARTDATE", "2014-12-01T00:00:00Z");

        HttpGet get = new HttpGet(builder.build());

        log.info("Calling PayPal service...");
        HttpResponse postResponse = client.execute(get);

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(postResponse.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";

        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        String stringResult = result.toString();
        log.info(URLDecoder.decode(stringResult, "UTF-8").replace("&L_", "\n"));
    }

    public static void main2(String[] args) throws IOException, URISyntaxException {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("https://www.sandbox.paypal.com/cgi-bin/webscr");

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("cmd", "_notify-synch"));
        urlParameters.add(new BasicNameValuePair("tx", "5LT6294914055140G"));
        urlParameters.add(new BasicNameValuePair("at", "p0wwIIaN8cBhebjsWPqui8C8dQRnayVbQzzeLw4GzJvAxugVeNL4ReUenfu"));
        urlParameters.add(new BasicNameValuePair("submit", "PDT"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        log.info("Calling PayPal Tx service...");
        HttpResponse postResponse = client.execute(post);

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(postResponse.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";

        while ((line = rd.readLine()) != null) {
            result.append(line + "\n");
        }
        String stringResult = result.toString();
        log.info(stringResult);
    }*/
}
